package account;

import interceptor.InjectConnection;

import java.sql.Connection;

import utils.Var;
import utils.TextUtils;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: Shawn
 * Date: 2009-6-2
 * Time: 22:32:14
 */
public class AccountAction {

  private Connection con;

  @InjectConnection
  public void setCon(Connection con) {
    this.con = con;
  }

  private AccountInfo accountInfo;

  public void setAccountInfo(AccountInfo accountInfo) {
    this.accountInfo = accountInfo;
  }

  public AccountInfo getAccountInfo() {
    return accountInfo;
  }

  public String addAccount() throws Exception {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (!AccountUtils.isAdmin(session)) throw new Exception("deny");

    accountInfo.setRights(getRights());
    accountInfo.setPassword(TextUtils.SHAString(accountInfo.getPassword()));

    int accountID = Account.addAccount(con, accountInfo);
    accountInfo.setAid(accountID);
    return Var.ACTION_SUCCESS;
  }

  public String modiAccount() throws Exception {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (!AccountUtils.isAdmin(session)) throw new Exception("deny");

    accountInfo.setRights(getRights());

    String password = Account.getAccountInfo(con, accountInfo.getAid()).getPassword();
    if (accountInfo.getPassword().trim().length() == 0) accountInfo.setPassword(password);
    else accountInfo.setPassword(TextUtils.SHAString(accountInfo.getPassword()));

    Account.modiAccount(con, accountInfo);
    return Var.ACTION_SUCCESS;
  }

  public String delAccount() throws Exception {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (!AccountUtils.isAdmin(session)) throw new Exception("deny");
    Account.delAccount(con, accountInfo.getAid());
    return Var.ACTION_SUCCESS;
  }

  private int getRights() {
    HttpServletRequest request = ServletActionContext.getRequest();
    String[] rights = request.getParameterValues("rights");
    if (rights == null) return 0;

    int right = 0;
    for (String r : rights) right += Integer.parseInt(r);
    return right;
  }
}
